/*
 *@author: YangJie
 *@date: 2021-04-09 10:49:49
 *@version:
 *@description: 参数设置->公共配置->班组
 */
 import React, { Component } from 'react';
 import { Table, Form, Card, Tabs, Modal } from 'antd';
 import '@/assets/css/settings';
 import * as Utils from '../../utils_yyr/action';
 import BasicForm from '../../components_yyr/common/basicFormbaobiao';
 import { FileDown } from '../../components_yyr/commponent/File';
 import Paging from '../../components_yyr/commponent/Paging';
 import Echarts from 'echarts-for-react';
//  import 'echarts-gl';
 import { euqApplicationName_sg, lotAuth, lotAuth2 } from '../../config';
 
 var date = new Date();
 let day = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate()
 let month = date.getMonth() + 1 ? `0${date.getMonth() + 1}` : date.getMonth() + 1
 let year = date.getFullYear()
 let todayEnd = `${year}-${month}-${day} 23:59:59`
 let todayStart = `${year}-${month}-01 00:00:00`
 const { TabPane } = Tabs;
 class departmentAnalyse extends Component {
 
     state = {
         loading: false, //加载中...
         dataSource: [], //数据源
         drawerVisible: false, //新增修改抽屉的显示与隐藏
         chooseData: {}, //用checkbox选择好的数据
         total: 0, //总数据量
         formValues: {
             pageNum: 1,
             pageSize: 10,
             startTime: todayStart,
             endTime: todayEnd,
         },
         weekList: [],
         value: '1',
         //  activeKey:'top',
         activeKey: 'top',
         panes: [],
         newTabIndex: 0,
         equipmentTypeChart: [],
         thisMonth: [], lastMonth: [], last90Day: [], dateString: [], EquTypeList: [], DepartmentList: [],
         loadingRecord: false,
         recordTable: [],
         total1: 0,
         formValues1:{
             pageNum: 1,
             pageSize: 10,
         }
     };
     constructor(props) {
         super(props);
         // console.log(props);
     }
     componentDidMount() {
         this.getDate()
         this.fetch({
             pageNum: 1,
             pageSize: 10,
             startTime: todayStart,
             endTime: todayEnd,
         });
         this.findEquTypePageList()
         this.queryTreeDepartment()
     }
     //初始化加载数据
     fetch = (data) => {
        this.setState({ loading: true, formValues: data })
         this.post(`${euqApplicationName_sg}/inspectionStandardExecute/findStandardExecute`, { data }).then(res => {
             let arr = res.data && res.data[0] ? res.data[0] : {}
             this.setState({
                 loading: false,
                 dataSource: res.data,
                 total: res.total,
             });
             this.findChart(arr)
         })
     }
     findChart = (data) => {
        let option1 = this.option1
        data = {...this.state.formValues,...data}
        this.post(`${euqApplicationName_sg}/inspectionStandardExecute/findStandardExecuteChart`, { data }).then(res1 => {
            let arr = res1.data
            option1.dataset.source = arr
            this.setState({ equipmentTypeChart: arr }, () => {
                this.echartRef1.getEchartsInstance().setOption(option1, true);
            })
        })
     }
     findEquTypePageList = () => {
         this.get(`${euqApplicationName_sg}/parameter_setting_equipmentType/findEquTypePageList`).then(res => {
             this.setState({
                 EquTypeList: res.data
             });
         })
     }
     queryTreeDepartment = () => {
        //  this.get(`${lotAuth}/department/queryTreeDepartment`).then(res => {
         this.get(`${lotAuth2}/department/queryTreeDepartment`).then(res => {
             this.setState({
                 DepartmentList: res.data
             });
         })
     }
     findInspectionRecordTable = (data) => {
         this.setState({ loadingRecord: true, formValues1: data })
         this.post(`${euqApplicationName_sg}/inspectionStandardExecute/findDetails`, { data }).then(res => {
             this.setState({
                 loadingRecord: false,
                 recordTable: res.data,
                 total1: res.total,
             });
         })
     }
     getDate = () => {
         var date = new Date();
         let day = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate()
         let month = date.getMonth() + 1 ? `0${date.getMonth() + 1}` : date.getMonth() + 1
         let year = date.getFullYear()
         let todayEnd = `${year}-${month}-${day} 23:59:59`
         let todayStart = `${year}-${month}-01 00:00:00`
         let thisMonth = [todayStart, todayEnd]
         let lastMonth = this.getLastMonth()
         let last90Day = [this.getLast90Day(), todayEnd]
         this.setState({
             thisMonth, lastMonth, last90Day
         })
     }
     getLastMonth = () => {//获取上个月日期第一天
         var nowDate = new Date();
         var year = nowDate.getFullYear();
         var month = nowDate.getMonth() < 10 ? `0${nowDate.getMonth()}` : nowDate.getMonth();
         if (month == 0) {
             year = year - 1;
             month = 12;
         }
         var lastDay = new Date(year, month, 0);
         var day = lastDay.getDate() < 10 ? `0${lastDay.getDate()}` : lastDay.getDate();
         var yyyyMMdd = year + "-" + month + "-" + day + ' 23:59:59';
         return [year + "-" + month + "-01 00:00:00", yyyyMMdd];
     }
     /**
      * 获取上个月月底日期
      */
     getLast90Day = () => {
         var nowDate = new Date();
         var year = nowDate.getFullYear();
         var month = nowDate.getMonth() - 2 < 10 ? `0${nowDate.getMonth() - 2}` : nowDate.getMonth() - 2;
         if (month == 0) {
             month = 12;
             year = year - 1;
         }
         var lastDay = new Date(year, month, 0);
         var day = lastDay.getDate() < 10 ? `0${lastDay.getDate()}` : lastDay.getDate();
         var yyyyMMdd = year + "-" + month + "-" + day + ' 00:00:00';
         return yyyyMMdd;
     }
     getXianTiOption = () => {
        var colors = ['#ffe27d','#fc944f','#85e6e9'];
        var labelOption = {
            normal: {
               show: true,
               position: 'top',
          }
       }
        const option = {
            title:{
                text:'导出图片',
                show:false
            },
            color: colors,
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                   type: 'shadow'
                }
            },
            grid: {
                right: '2%',
                left: '2%',
                containLabel: true
            },
            toolbox: {
                feature: {
                    // dataView: {show: true, readOnly: false},
                    // restore: {show: true},
                    saveAsImage: { show: true, title: '导出图' }
                }
            },
            legend: {
                data: ['正常', '遗漏', '异常']
            },
            dataset: {
               dimensions: ['dayAll', 'normal', 'leaveOut', 'abnormal'],
               source: []
           },
            xAxis: {
                type: 'category',
            },
            yAxis: {},
            series: [
                {
                    name: '正常',
                   //  data: [],
                    type: 'bar',
                    barWidth: 50,
                    label: labelOption
                },
                {
                    name: '遗漏',
                   //  data: [],
                    type: 'bar',
                    barWidth: 50,
                    label: labelOption
                },
                {
                    name: '异常',
                   //  data: [],
                    type: 'bar',
                    barWidth: 50,
                    label: labelOption
                },
            ],
            dataZoom: [
                {
                    type: 'inside',
                    show: true,
                    xAxisIndex: [0],
                    // 缩放的开始位置的百分比，0 - 100
                    start: 1,
                    // 缩放的结束位置的百分比，0 - 100
                    end: 100,
                    // 缩放的开始位置的数值，只有在工具栏的缩放行为的事件中存在。
                    // startValue?: number,
                    // 缩放的结束位置的数值，只有在工具栏的缩放行为的事件中存在。
                    // endValue?: number
                }
            ]
        };
        this.option1 = option
        return option;
    };
     onChangeTabs = activeKey => {
         console.log(activeKey)
         this.setState({ activeKey });
     };
 
     onEdit = (targetKey, action) => {
         this[action](targetKey);
     };
 
     //表单查询
     filterSubmit = values => {
         console.log(values)
         values.startTime = values.startTime_endTime && values.startTime_endTime.length === 2 ? Utils.getDate(values.startTime_endTime[0]) + ' 00:00:00' : ''
         values.endTime = values.startTime_endTime && values.startTime_endTime.length === 2 ? Utils.getDate(values.startTime_endTime[1]) + ' 23:59:59' : ''
         delete values['startTime_endTime']
         let data = { ...this.state.formValues, ...values }
         console.log(data)
         this.fetch(data);
     };
     //头部关键字查询部分
     formList = () => {
         const { EquTypeList, formValues, DepartmentList } = this.state;
         const formList = [
             { type: "TIMEFRAME", label: "时间", field: "startTime_endTime", allowClear: true, initialValue: [formValues.startTime, formValues.endTime] ,required:true},
             { type: 'TREESELECT', label: '部门', field: 'depIdList', name: 'name', valueField: 'id', allowClear: true, list: DepartmentList, multiple: true },
             { type: 'TREESELECT', label: '类型', field: 'equTypeList', name: 'name', valueField: 'id', allowClear: true, list: EquTypeList, multiple: true },
             { type: 'INPUT', label: '设备名称', field: 'equName', allowClear: true },
 
         ];
         return formList;
     };
     jump = (record) => {
         this.setState({
             drawerVisible: true
         })
         record.pageNum = 1
         record.pageSize = 10
         this.findInspectionRecordTable(record)
     }
     closeModal = () => {
         this.setState({
             drawerVisible: false
         })
     }
     onRowClick = (record) => {
        this.findChart(record)
    }
     render() {
         const {  dataSource, loading, total, formValues,loadingRecord,total1, formValues1 ,recordTable ,drawerVisible} = this.state;
         const columns = [
             {
                title: '详细', width: 100, dataIndex: 'notScanCount', render: (text, record) => {
                    return <a onClick={() => { this.jump(record) }}>详细</a>
                },align:'center',
            },
             { title: '设备编码', width: 100, dataIndex: 'equCode' ,align:'center',},
             { title: '设备名称', width: 100, dataIndex: 'equName',align:'center', },
             { title: '标准项名称', width: 100, dataIndex: 'standardName' ,align:'center',},
             { title: '应检总数', width: 100, dataIndex: 'shouldInsCount' ,align:'center',},
             { title: '跳过', width: 100, dataIndex: 'skip',align:'center', },
             { title: '异常', width: 100, dataIndex: 'abnormal' ,align:'center',},
             { title: '遗漏', width: 100, dataIndex: 'leakDetection' ,align:'center',},
             { title: '异常率（%）', width: 100, dataIndex: 'abnormalRate' ,align:'center',},
             {
                 title: '遗漏率（%）', width: 100, dataIndex: 'leakDetectionRate',align:'center',
             },
         ]
         const p = this
         const modalProps = {
             title: "详细",
             visible: drawerVisible,
             width: '880px',
             onCancel() {
                 p.closeModal();
             },
             okText: '保存',
             cancelText: '取消',
             onOk() {
                 p.modalSubmitPeo();
             },
             footer:null
         };
         const columns1 = [
             // { title: '序号', width: 100, dataIndex: 'id' },
             { title: '巡检结果', dataIndex: 'result' ,render:(text)=>{
                 return <span style={{color:text==='遗漏'?'#fc944f':text==='异常'?'#85e6e9':text==='正常'?'#ffe27d':'black'}}>{text}</span>
             },align:'center',},
             { title: '设备编码', width: 100, dataIndex: 'equCode',align:'center', },
             { title: '设备名称', width: 100, dataIndex: 'equName',align:'center', },
             { title: '计划名称', dataIndex: 'planName',align:'center', },
             { title: '标准名称', dataIndex: 'standardName',align:'center', },
             { title: '计划时间', dataIndex: 'planTime',align:'center', },
             { title: '参考值', dataIndex: 'upperLimit' ,render:(text,record)=>{
                return text&&record.lowerLimit ? `${text}:${record.lowerLimit}` : record.normalValue&&record.outliersValue ? `${record.normalValue}:${record.outliersValue}` : ''
             },align:'center',},
             { title: '巡检值',dataIndex: 'inspectionValue',align:'center', },
         ]
         return (
             <div className="shadow-radius">
                 <Tabs hideAdd
                     onChange={this.onChangeTabs}
                     activeKey={this.state.activeKey}
                     type="editable-card"
                     onEdit={this.onEdit}>
                     <TabPane tab="巡检标准执行统计" key="top" closable={false}>
                         <Card>
                             <BasicForm formList={this.formList()} filterSubmit={this.filterSubmit} labelSpan={8} wrapperSpan={12} onRef={ref => (this.child = ref)} />
                         </Card>
                         <div>
                             <Tabs defaultActiveKey="1" tabBarExtraContent={<>
                                 <FileDown fileName="巡检标准执行统计报表" buttonName="导出表" method="post" apiPath={`${euqApplicationName_sg}/inspectionStandardExecute/exportStandardExecute`} data={{...this.state.formValues}} />
                             </>}>
                                 <TabPane tab="维保次数趋势" key="1">
                                    <div style={{ display: 'flex' }}>
                                         <Echarts
                                             option={this.getXianTiOption()}
                                             style={{ width: '100%', height: '460px' }}
                                             ref={(e) => { this.echartRef1 = e; }}
                                         />
                                     </div>
                                     <div>
                                         <Table columns={columns} rowKey={(record, index) => index} dataSource={dataSource} pagination={false} loading={loading}  onRowClick={(record)=>{this.onRowClick(record)}} scroll={{ x: 'calc(700px + 50%)' }}/>
                                         <Paging total={total} formValues={formValues} fetch={pager => this.fetch(pager)} />
                                     </div>
                                 </TabPane>
                             </Tabs>
                         </div>
                     </TabPane>
                 </Tabs>
                 <Modal {...modalProps}>
                     <div style={{marginBottom:10}}>
 
                      <Table columns={columns1} rowKey={(record, index) => record.planCode} dataSource={recordTable} pagination={false} loading={loadingRecord}  scroll={{ y: 400 }}/>
                     </div>
                     <div>
                         <Paging total={total1} formValues={formValues1} fetch={pager => this.findInspectionRecordTable(pager)} />
                     </div>
                 </Modal>
             </div>
         );
     }
 }
 export default Form.create()(departmentAnalyse);
 